<template>
  <div class="hello">
    <input type="text" v-model="userName">
    <XjrButton @clickEvent="btnEvent" :disabled="false" size="sm">发送</XjrButton>
    <XjrButton @clickEvent="handlerEvent" :disabled="false" size="sm">打开连接</XjrButton>

    <xjr-editor  @sendMessageFunc="btnEvent" style="margin-left: 500px" ref="editor"  :catchData="getChatContent"></xjr-editor>
  </div>
</template>

<script>
    import XjrButton from "./XjrButton";
    import XjrEditor from "./XjrEditor";
export default {
  name: 'HelloWorld',
    components: {XjrEditor, XjrButton},
    data () {
    return {
      msg: 'Welcome to Your Vue.js App',
        websocket:null,
        chatContent:'',
        userName:''
    }
  },
    methods:{
        handlerEvent(){
            let g=this;
            if (/\s/.test(g.userName) || g.userName==""){
                alert("先输入你的昵称！");
                return;
            }
           g.websocket=new WebSocket("ws://www.sophi.store:9378/Sophi/websocket/"+g.userName);
            g.websocket.onopen=function () {
               alert("成功连接");
           }
            g.websocket.onmessage=function (evt) {
                let str=evt.data;
                if (new RegExp(g.userName,'g').test(evt.data)){
                     str=evt.data;
                    str=str.replace(new RegExp("left"),"right");
                }
                g.$refs.editor.$refs.content.innerHTML+=str;
                g.$refs.editor.$refs.content.scrollTop=g.$refs.editor.$refs.content.scrollHeight;
            }
            g.websocket.onclose=function () {
                g.websocket.close();
            }

        },
        btnEvent(e){
            this.$refs.editor.editor.txt.clear();
            this.websocket.send(this.chatContent);
        },
        getChatContent(e){
            this.chatContent=e;
        }
    },
  mounted() {

  }


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
